#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <cstdio>
#include <cstring>
#include <fcntl.h>
#include <signal.h>
#include <pthread.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <vector>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <functional>
#include <semaphore.h>
#include <jsoncpp/json/json.h>
#include <sys/select.h>
void usage(std::string proc)
{
    std::cout << "\nUsage: " << proc << " serverIp serverPort\n"
              << std::endl;
}
using namespace std;
// ./tcp_client targetIp targetPort
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        usage(argv[0]);
        exit(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);
    int sock = 0;
    std::string line;
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        std::cerr << "socket error" << std::endl;
        exit(2);
    }
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0)
    {
        std::cerr << "connect error" << std::endl;
        exit(3); // TODO
    }
    std::cout << "connect success" << std::endl;
    while (true) // TODO
    {

        std::cout << "请输入# ";
        std::getline(std::cin, line);
        if (line == "quit")
            break;
        ssize_t s = send(sock, line.c_str(), line.size(), 0);
	  char buffer[1024];
        memset(buffer,0,sizeof buffer);
        recv(sock,buffer,sizeof buffer,0);
        cout<<buffer<<endl;
    }

    return 0;
}
